package com.ruoyi.framework.login.api;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import lombok.experimental.UtilityClass;

/**
 * 全链路追踪
 * thirdSession工具类
 *
 * @author byChen
 */
@UtilityClass
public class ApiSessionHolder {
    private final ThreadLocal<Object> THREAD_LOCAL_THIRD_SESSION = new TransmittableThreadLocal<>();

    /**
     * TTL 设置 当前登录学员信息
     *
     * @param obj 登录用户信息
     */
    public void setSessionObj(Object obj) {
        THREAD_LOCAL_THIRD_SESSION.set(obj);
    }

    /**
     * 获取TTL中的LoginStudent
     *
     * @return 登录学员信息
     */
    public Object getSessionObj() {
        return THREAD_LOCAL_THIRD_SESSION.get();
    }

    /**
     * 获取 SessionObj 的id信息
     *
     * @return id数
     */
    public Long getSessionObjId() {
        Object sessionObj = getSessionObj();
        if (sessionObj == null) {
            return null;
        }
        Object id = ReflectUtil.getFieldValue(sessionObj, "id");
        if (id == null) {
            return null;
        }
        if (id instanceof Long) {
            return (Long) id;
        }
        return null;
    }

    /**
     * 清除
     */
    public void clear() {
        THREAD_LOCAL_THIRD_SESSION.remove();
    }
}
